<template>
  <div>
    <el-dialog v-model="props.dialogManufacture" title="制作" :before-close="handleManufactureClose" width="800px">
      <el-tabs v-model="radio1" type="card" @tab-change="tabChange">
        <el-tab-pane label="满减券" name="full" :disabled="disabledFull" />
        <el-tab-pane label="包邮券" name="mail" :disabled="disabledMail" />
        <el-tab-pane label="折扣价" name="price" :disabled="disabledPrice" />
      </el-tabs>

      <el-form label-position="left" :model="subtractionFrom" label-width="auto" :rules="publicRules" ref="fullFormRef">
        <el-form-item label="发放站点" prop="newWebsite">
          <el-select style="width: 100%" v-model="subtractionFrom.newWebsite" placeholder="请选择"
            @change="changeAllWebsite">
            <el-option v-for="dict in sys_web_site" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="labelName" prop="amount" :required="handover" v-show="handover">
          <el-input v-model.trim="subtractionFrom.amount" type="number" placeholder="请输入" :min="1"><template #append
              v-if="newUnit">{{ newUnit }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="使用条件" prop="threshold">
          <el-input minlength="1" maxlength="20" placeholder="请输入" v-model.trim="subtractionFrom.threshold">
            <template #prepend>订单满</template>
            <template #append>{{sys_web_site.find(e => e.id ===
              subtractionFrom.newWebsite)?.currencyCode}}可使用</template>
          </el-input>
        </el-form-item>
        <el-form-item label="有效期" prop="newTime" :required="!showTime">
          <el-date-picker v-model="subtractionFrom.newTime" type="daterange" range-separator="至"
            start-placeholder="开始时间" end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
            time-format="A hh:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" :disabled="showTime" />
          <el-checkbox v-model="subtractionFrom.longTerm" label="长期（有效期以UTC时间为标准）" style="margin-left: 20px"
            @change="changeLongTerm" />
        </el-form-item>
        <el-form-item label="优惠码" prop="code" required>
          <el-input maxlength="4" v-model.trim="subtractionFrom.code" placeholder="优惠码">
            <template #append>
              <el-button @click="random">随机生成</el-button></template>
          </el-input>
        </el-form-item>
        <el-form-item prop="descriptions" required>
          <MoreLanguage :newList="subtractionFrom.descriptions" label="满减券名称" @publicCheck="publicCheck"></MoreLanguage>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog">
          <div>
            <el-button type="primary" @click="handlePublicAdd">添加</el-button>
            <el-button type="danger" @click="handlePublicDelete">删除</el-button>
          </div>
          <div>
            <el-button @click="handleManufactureClose">取消</el-button>
            <el-button type="primary" @click="handleManufactureSure">保存
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, defineProps, defineEmits, onMounted, watch } from "vue";
const { proxy } = getCurrentInstance();
const emits = defineEmits(["handleManufactureClose", "handleManufactureSure"]);
const props = defineProps({
  //   full：满减，mail：包邮
  choseTag: {
    type: String,
    default: "" || "full",
  },
  manufactureItem: {
    type: Object,
    default: {},
  },
  //   默认隐藏
  dialogManufacture: {
    type: Boolean,
    default: false,
  },
});
watch(
  () => props.dialogManufacture,
  () => {
    if (props.dialogManufacture) return getHandel();
  }
);
const radio1 = ref('')
const sys_web_site = ref([])
const showTime = ref(false); //默认是满减券可以选择有效期
const isEditing = ref(false); //是否是编辑默认是新增

const disabledFull = ref(false); //是否是编辑默认是新增
const disabledMail = ref(false); //是否是编辑默认是新增
const disabledPrice = ref(false); //是否是编辑默认是新增
const checkedSubtraction = ref([]); //多语言勾选的内容

const handover = ref(true); //切换选择的类型默认true是fuil
const newUnit = ref('')
const labelName = ref('')


const subtractionFrom = ref({
  amount: null, //面值
  websiteIds: [], //站点
  newWebsite: null,//站点===需要删除
  threshold: 0, //使用条件
  startDate: "", //开始日期
  endDate: "", //结束日期
  longTerm: false, //是否长期有效
  code: "", //优惠码
  descriptions: [
    // languageId:null,//语言id
    // name:''//优惠券名称
  ], //多语言
  couponType: "fullReduction", //满减券类型
  newTime: [], //有效期时间，需要删除
}); //满减券表单参数

const handleManufactureSure = (formEl) => {
  proxy.$refs["fullFormRef"].validate((valid) => {
    if (valid) {
      if (!proxy.publicArray(subtractionFrom.value.descriptions))
        return proxy.$modal.msgError("请完整填写");
      if (hasDuplicateLanguageIds(subtractionFrom.value.descriptions))
        return proxy.$modal.msgError("语言类型不能重复");

      if (subtractionFrom.value.newTime.length) {
        subtractionFrom.value.startDate = proxy.convertTime(
          1,
          subtractionFrom.value.newTime[0]
        );
        subtractionFrom.value.endDate = proxy.convertTime(
          1,
          subtractionFrom.value.newTime[1]
        );
      }

      if (subtractionFrom.value.couponType === 'freeShipping') {
        delete subtractionFrom.value.amount
      }
      subtractionFrom.value.websiteIds = []
      subtractionFrom.value.websiteIds.push(subtractionFrom.value.newWebsite)
      if (!isEditing.value) {
        site.SiteCoupon.add({
          data: subtractionFrom.value,
        }).then((res) => {
          if (res.code !== 200) return;
          proxy.$modal.msgSuccess("添加成功");
          handleCancel();
          emits("handleManufactureSure");
        });
      } else {
        site.SiteCoupon.update({
          pathParams: {
            id: props.manufactureItem.id,
          },
          data: subtractionFrom.value,
        }).then((res) => {
          if (res.code !== 200) return;
          proxy.$modal.msgSuccess("修改成功");
          handleCancel();
          emits("handleManufactureSure");
        });
      }

    }
  })
}
const changeAllWebsite = (e) => {
  newUnit.value = ''
  if (subtractionFrom.value.couponType === 'discount') {
    newUnit.value = '%'
  } else {
    newUnit.value = sys_web_site.value.find(code => code.id === e)?.currencyCode
  }
  // if (e) return proxy.$refs["fullFormRef"].clearValidate('newWebsite')
};
const tabChange = (e) => {
  radio1.value = e
  if (e === "full") {
    subtractionFrom.value.couponType = "fullReduction";
    labelName.value = '面值'
    handover.value = true
    newUnit.value = sys_web_site.value.find(code => code.id === subtractionFrom.value.newWebsite)?.currencyCode
  } else if (e === "price") {
    subtractionFrom.value.couponType = "discount";
    labelName.value = '折扣'
    handover.value = true
    newUnit.value = '%'
  } else {
    labelName.value = '面值'
    handover.value = false
    newUnit.value = sys_web_site.value.find(code => code.id === subtractionFrom.value.newWebsite)?.currencyCode
    subtractionFrom.value.couponType = "freeShipping";
  }
  subtractionFrom.value.amount = null;
  proxy.$refs["fullFormRef"].clearValidate()
}

const changeLongTerm = (e) => {
  showTime.value = e;
  subtractionFrom.value.newTime = [];
  subtractionFrom.value.startDate = "";
  subtractionFrom.value.endDate = "";
  console.log(e);
  proxy.$refs["fullFormRef"].clearValidate()
};

const publicRules = ref({
  // 面值
  amount: [
    { required: true, message: "请选择", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        let newPattern
        const { couponType } = subtractionFrom.value || {};
        if (couponType === 'fullReduction') {
          newPattern = /^(?:[1-9][0-9]{0,2}|0)(?:\.\d{1,2})?$/;
          if (!newPattern.test(value))
            return callback(new Error("只能输入1~999的正数（最多两位小数）"));
        } else if (couponType === 'discount') {
          newPattern = /^(?:[1-9]|[1-4][0-9]|50)(?:\.\d{1,2})?$/;
          if (!newPattern.test(value))
            return callback(new Error("请输入1%~50%的折扣（最多两位小数）"));
        }
        callback();
      },
      trigger: 'blur'
    },
  ],
  // 使用条件
  threshold: [
    {
      validator: (rule, value, callback) => {
        let newPattern
        const { amount, threshold, couponType } = subtractionFrom.value;
        if (couponType === 'discount') {
          newPattern = /^\d+(\.\d{1,2})?$/;
          if (!newPattern.test(value))
            return callback(new Error("只能输入正数小数点两位"));
        } else {
          newPattern = /^(0|[1-9]\d*)$/;
          if (!newPattern.test(value))
            return callback(new Error("只能输入正整数"));
          if (!handover.value) return callback();
          if (amount && threshold >= amount * 2) return callback();
          callback(new Error("使用条件必须大于面值的2倍"));
        }
        callback();
      },
      trigger: "blur",
    },
  ],
  newWebsite: [{ required: true, message: "请选择", trigger: "blur" }],//站点
  // 有效期时间
  newTime: [{ required: true, message: "请选择", trigger: "blur" }],
  // 优惠码
  code: [
    { required: true, message: "请输入", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9]+$/,
      message: "请正确输入",
      trigger: "blur",
    },
  ],
});

onMounted(() => {
  getWebsite()
})
const getWebsite = () => {
  let from = {
    pageNum: 1,
    pageSize: 999,
    param: {
      status: 1, //状态
      publishStatus: ['Succeed', 'Failed'],
    },
  }
  site.general
    .sitewebsiteList({
      data: from,
    })
    .then((res) => {
      sys_web_site.value = res.data;
    })
}
const getHandel = () => {
  subtractionFrom.value.descriptions = [];
  radio1.value = props.choseTag
  if (Object.keys(props.manufactureItem).length) {
    // 编辑
    isEditing.value = true;
    getDetails();
  } else {
    isEditing.value = false;
    handover.value = true
    labelName.value = '面值'
    // 新增
    var publicObj = {
      languageId: 1,
      name: "",
    };
    subtractionFrom.value.descriptions.push(publicObj);
  }
}
// 取消事件
const handleManufactureClose = () => {
  handleCancel();
  emits("handleManufactureClose");
};
const handleCancel = () => {
  proxy.resetForm("fullFormRef");
  showTime.value = false;
  disabledFull.value = false;
  disabledMail.value = false;
  disabledPrice.value = false;
  handover.value = false;
  newUnit.value = ''
  subtractionFrom.value.longTerm = false;
  subtractionFrom.value.amount = null;
  subtractionFrom.value.websiteIds = [];
  subtractionFrom.value.newWebsite = null;
  subtractionFrom.value.threshold = 0;
  subtractionFrom.value.startDate = '';
  subtractionFrom.value.endDate = '';

  subtractionFrom.value.code = '';
  subtractionFrom.value.couponType = 'fullReduction';
  subtractionFrom.value.newTime = [];
};
/** 公共添加 */
const handlePublicAdd = () => {
  var publicObj = {
    languageId: null,
    name: "",
  };
  subtractionFrom.value.descriptions.push(publicObj);
};
/** 公共删除 */
const handlePublicDelete = () => {
  if (checkedSubtraction.value.length == 0) {
    proxy.$modal.msgError("请勾选");
  } else {
    subtractionFrom.value.descriptions =
      subtractionFrom.value.descriptions.filter(
        (item) => !checkedSubtraction.value.includes(item.index)
      );
    checkedSubtraction.value = [];
  }
};
/** 复选框选中数据 */
const publicCheck = (selection) => {
  checkedSubtraction.value = selection;
};
// 随机生成事件
const random = () => {
  site.SiteCoupon.generateCode({}).then((res) => {
    if (res.code !== 200) return;
    subtractionFrom.value.code = res.data.code;
  });
};
const getDetails = () => {
  site.SiteCoupon.getById({
    pathParams: {
      id: props.manufactureItem.id,
    },
  }).then((res) => {
    console.log(res.data, '详情');
    if (res.data.couponType === 'fullReduction') {
      disabledMail.value = true;
      disabledPrice.value = true;
      // 满减券
      handover.value = true
      labelName.value = '面值'

    } else if (res.data.couponType === 'freeShipping') {
      disabledPrice.value = true;
      disabledFull.value = true;
      // 包邮券

    } else {
      disabledMail.value = true;
      disabledFull.value = true;

      handover.value = true
      labelName.value = '折扣'
      // 折扣价
    }
    subtractionFrom.value.couponType = res.data.couponType
    subtractionFrom.value.amount = res.data.amount
    subtractionFrom.value.newWebsite = res.data.websiteIds[0];
    subtractionFrom.value.code = res.data.code
    let newStartDate = proxy.DateTime(res.data.startDate);
    let newEndDate = proxy.DateTime(res.data.endDate);
    subtractionFrom.value.newTime.push(newStartDate);
    subtractionFrom.value.newTime.push(newEndDate);
    subtractionFrom.value.longTerm = res.data.longTerm
    subtractionFrom.value.threshold = res.data.threshold
    if (res.data.longTerm) {
      showTime.value = true;
    } else {
      showTime.value = false;
    }
    subtractionFrom.value.descriptions = res.data.descriptions;
  })
}
const hasDuplicateLanguageIds = (arr) => {
  const seen = new Set(); // 用于存储已经遇到的 languageId
  for (let item of arr) {
    if (seen.has(item.languageId)) {
      return true; // 如果发现重复值，返回 true
    }
    seen.add(item.languageId); // 否则添加到集合中
  }
  return false; // 如果循环结束后没有发现重复值，返回 false
};

</script>
<style lang="scss" scoped>
.dialog {
  display: flex;
  justify-content: space-between;
  /* 左右两边对齐 */
}
</style>